<template>
  <view class="vehicle-internal-verify-page page-content">
    <!-- 创建任务弹窗 -->
    <CreateTaskModal
      :show="createTaskModalVisible"
      @update:show="createTaskModalVisible = $event"
      @confirm="confirmCreateTask"
    />
    
    <!-- 执行未确认操作弹窗 -->
    <UnconfirmedOrderModal
      :show="unconfirmedModalVisible"
      @update:show="unconfirmedModalVisible = $event"
      :orderData="currentOrder"
      @confirm="confirmUnconfirmedOrder"
    />
    
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="场内车辆核验" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @click="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="header-sticky">
          <view class="header-container">
            <!-- 统计卡片区域 -->
            <view class="stats-section">
              <view class="stats-cards">
                <view class="stats-card">
                <view class="stats-icon">
                  <uni-icons type="bars" size="48" color="#1890ff"></uni-icons>
                </view>
                <view class="stats-content">
                  <text class="stats-label">总任务数</text>
                  <text class="stats-number">{{ totalTasks }}</text>
                </view>
              </view>
              
              <view class="stats-card">
                <view class="stats-icon">
                  <uni-icons type="checkmarkempty" size="48" color="#52c41a"></uni-icons>
                </view>
                <view class="stats-content">
                  <text class="stats-label">已完成</text>
                  <text class="stats-number">{{ completedTasks }}</text>
                </view>
              </view>
              
              <view class="stats-card">
                <view class="stats-icon">
                  <uni-icons type="spinner-cycle" size="48" color="#fa8c16"></uni-icons>
                </view>
                <view class="stats-content">
                  <text class="stats-label">进行中</text>
                  <text class="stats-number">{{ inProgressTasks }}</text>
                </view>
              </view>
              
              <view class="stats-card">
                <view class="stats-icon">
                  <uni-icons type="info" size="48" color="#f5222d"></uni-icons>
                </view>
                <view class="stats-content">
                  <text class="stats-label">未确认订单</text>
                  <text class="stats-number">{{ unconfirmedOrders }}</text>
                </view>
              </view>
              </view>
            </view>
            
            <!-- 操作按钮区域 -->
            <view class="action-section">
              <up-button 
                type="primary" 
                @click="handleCreateTask"
                text="创建核验任务"
                :customStyle="{
                  width: '200rpx',
                  height: '70rpx',
                  fontSize: '28rpx',
                  marginRight: '20rpx'
                }"
              >
              </up-button>
              
              <up-button 
                type="warning" 
                @click="handleUnconfirmedOrders"
                text="处理未确认订单"
                :customStyle="{
                  width: '220rpx',
                  height: '70rpx',
                  fontSize: '28rpx'
                }"
              >
              </up-button>
            </view>
            
            <!-- 搜索区域 -->
            <view class="search-container">
              <view class="search-input-wrapper">
                <up-search 
                  v-model="searchKeyword" 
                  :clearabled="true" 
                  :showAction="false"
                  placeholder="任务名称/车牌号/执行人" 
                  @search="handleSearch" 
                  @clear="handleClear"
                  shape="round"
                  bgColor="#ffffff"
                >
                </up-search>
              </view>
              <up-button 
                type="primary" 
                size="small" 
                @click="handleSearch"
                shape="circle"
                text="搜索"
                :customStyle="{
                  marginLeft: '20rpx',
                  height: '70rpx',
                  minWidth: '100rpx',
                  fontSize: '26rpx'
                }"
              >
              </up-button>
            </view>
            
            <!-- 选项卡 -->
            <view class="tabs-container">
              <up-tabs 
                :list="tabsList" 
                :scrollable="false" 
                @change="handleTabChange"
                :customStyle="{
                  backgroundColor: 'transparent'
                }"
              >
              </up-tabs>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 任务列表 -->
      <view class="task-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index"
          @click="handleTaskClick(item)">
          <view class="card-header">
            <view class="title">
              任务名称：<text class="task-name">{{ item.taskName }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">创建时间：</text>
                <text class="value">{{ item.createTime }}</text>
              </view>
              <view class="item">
                <text class="label">执行人：</text>
                <text class="value">{{ item.executor }}</text>
              </view>
              <view class="item">
                <text class="label">核验车辆数：</text>
                <text class="value">{{ item.vehicleCount }}</text>
              </view>
              <view class="item">
                <text class="label">完成进度：</text>
                <text class="value">{{ item.completedCount }}/{{ item.totalCount }}</text>
              </view>
            </view>
            
            <view class="card-footer">
              <view class="progress-bar">
                <view class="progress-bg">
                  <view class="progress-fill" :style="{ width: getProgressWidth(item) }"></view>
                </view>
                <text class="progress-text">{{ getProgressPercent(item) }}%</text>
              </view>
              
              <view class="operate">
                <up-button 
                  v-if="item.status === 'in_progress'" 
                  type="primary" 
                  text="查看详情" 
                  class="custom-style" 
                  @click.stop="handleViewDetail(item)"
                >
                </up-button>
                <up-button 
                  v-if="item.status === 'completed'" 
                  type="success" 
                  text="查看结果" 
                  class="custom-style" 
                  @click.stop="handleViewResult(item)"
                >
                </up-button>
                <up-button 
                  v-if="item.unconfirmedCount > 0" 
                  type="warning" 
                  text="处理未确认" 
                  class="custom-style" 
                  @click.stop="handleUnconfirmed(item)"
                >
                </up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import CreateTaskModal from './components/CreateTaskModal.vue'
import UnconfirmedOrderModal from './components/UnconfirmedOrderModal.vue'
import uniIcons from '@/components/uni-icons/components/uni-icons/uni-icons.vue'

// 组件已通过import自动注册

// 响应式数据
const paging = ref()
const currentList = ref([])
const searchKeyword = ref('')
const createTaskModalVisible = ref(false)
const unconfirmedModalVisible = ref(false)
const currentOrder = ref(null)

// 统计数据
const totalTasks = ref(0)
const completedTasks = ref(0)
const inProgressTasks = ref(0)
const unconfirmedOrders = ref(0)

// 选项卡数据
const tabsList = ref([
  { name: '全部任务' },
  { name: '进行中' },
  { name: '已完成' },
  { name: '已暂停' }
])

const currentTab = ref(0)

// 页面加载
onLoad((options) => {
  console.log('场内车辆核验页面加载', options)
})

onShow(() => {
  loadStatistics()
  paging.value?.reload()
})

onMounted(() => {
  loadStatistics()
  // 确保数据列表加载
  setTimeout(() => {
    paging.value?.reload()
  }, 100)
})

// 加载统计数据
const loadStatistics = async () => {
  try {
    // TODO: 调用API获取统计数据
    // const res = await getInternalVerifyStatistics()
    // 模拟数据
    totalTasks.value = 25
    completedTasks.value = 18
    inProgressTasks.value = 5
    unconfirmedOrders.value = 12
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 查询列表数据
const queryList = async (pageNo: number, pageSize: number) => {
  try {
    // TODO: 调用API获取任务列表
    // const params = {
    //   pageNo,
    //   pageSize,
    //   keyword: searchKeyword.value,
    //   status: getStatusByTab(currentTab.value)
    // }
    // const res = await getInternalVerifyTaskList(params)
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        taskName: '2024年1月场内车辆核验',
        status: 'in_progress',
        createTime: '2024-01-15 09:00:00',
        executor: '张三',
        vehicleCount: 150,
        completedCount: 120,
        totalCount: 150,
        unconfirmedCount: 5
      },
      {
        id: 2,
        taskName: '春节前车辆核验专项',
        status: 'completed',
        createTime: '2024-01-10 14:30:00',
        executor: '李四',
        vehicleCount: 200,
        completedCount: 200,
        totalCount: 200,
        unconfirmedCount: 0
      }
    ]
    
    paging.value?.complete(mockData)
  } catch (error) {
    console.error('查询列表失败:', error)
    paging.value?.complete([])
  }
}

// 返回按钮点击
const handleBackClick = () => {
  uni.navigateBack()
}

// 创建任务
const handleCreateTask = () => {
  createTaskModalVisible.value = true
}

// 确认创建任务
const confirmCreateTask = async (taskData: any) => {
  try {
    // TODO: 调用API创建任务
    // await createInternalVerifyTask(taskData)
    uni.showToast({
      title: '任务创建成功',
      icon: 'success'
    })
    loadStatistics()
    paging.value?.reload()
  } catch (error) {
    console.error('创建任务失败:', error)
    uni.showToast({
      title: '创建失败',
      icon: 'error'
    })
  }
}

// 处理未确认订单
const handleUnconfirmedOrders = () => {
  uni.navigateTo({
    url: '/pages/vehicle-internal-verify/unconfirmed-orders'
  })
}

// 搜索
const handleSearch = () => {
  paging.value?.reload()
}

// 清空搜索
const handleClear = () => {
  searchKeyword.value = ''
  paging.value?.reload()
}

// 选项卡切换
const handleTabChange = (index: number) => {
  currentTab.value = index
  paging.value?.reload()
}

// 任务点击
const handleTaskClick = (item: any) => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/detail?id=${item.id}`
  })
}

// 查看详情
const handleViewDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/detail?id=${item.id}`
  })
}

// 查看结果
const handleViewResult = (item: any) => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/result?id=${item.id}`
  })
}

// 处理未确认
const handleUnconfirmed = (item: any) => {
  currentOrder.value = item
  unconfirmedModalVisible.value = true
}

// 确认处理未确认订单
const confirmUnconfirmedOrder = async (orderData: any) => {
  try {
    // TODO: 调用API处理未确认订单
    // await handleUnconfirmedOrder(orderData)
    uni.showToast({
      title: '处理成功',
      icon: 'success'
    })
    loadStatistics()
    paging.value?.reload()
  } catch (error) {
    console.error('处理未确认订单失败:', error)
    uni.showToast({
      title: '处理失败',
      icon: 'error'
    })
  }
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const statusMap = {
    'pending': 'status-pending',
    'in_progress': 'status-progress',
    'completed': 'status-completed',
    'paused': 'status-paused'
  }
  return statusMap[status] || 'status-pending'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    'pending': '待开始',
    'in_progress': '进行中',
    'completed': '已完成',
    'paused': '已暂停'
  }
  return statusMap[status] || '未知'
}

// 获取进度宽度
const getProgressWidth = (item: any) => {
  const percent = (item.completedCount / item.totalCount) * 100
  return `${Math.min(percent, 100)}%`
}

// 获取进度百分比
const getProgressPercent = (item: any) => {
  const percent = (item.completedCount / item.totalCount) * 100
  return Math.round(Math.min(percent, 100))
}

// 根据选项卡获取状态
const getStatusByTab = (tabIndex: number) => {
  const statusMap = {
    0: '', // 全部
    1: 'in_progress', // 进行中
    2: 'completed', // 已完成
    3: 'paused' // 已暂停
  }
  return statusMap[tabIndex] || ''
}
</script>

<style lang="scss" scoped>
.vehicle-internal-verify-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header-sticky {
  background-color: #f5f5f5;
  z-index: 99;
}

.header-container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

// 统计卡片样式
.stats-section {
  margin-bottom: 30rpx;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.stats-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  
  &:nth-child(1) {
    border-left: 4rpx solid #1890ff;
  }
  
  &:nth-child(2) {
    border-left: 4rpx solid #52c41a;
  }
  
  &:nth-child(3) {
    border-left: 4rpx solid #fa8c16;
  }
  
  &:nth-child(4) {
    border-left: 4rpx solid #f5222d;
  }
}

.stats-icon {
  margin-right: 20rpx;
  
  .icon-text {
    font-size: 48rpx;
  }
}

.stats-content {
  flex: 1;
  
  .stats-label {
    display: block;
    font-size: 24rpx;
    color: #666666;
    margin-bottom: 8rpx;
  }
  
  .stats-number {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
}

// 操作按钮样式
.action-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30rpx;
}

// 搜索样式
.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.search-input-wrapper {
  flex: 0 0 500rpx;
}

// 选项卡样式
.tabs-container {
  margin-bottom: 20rpx;
}

// 列表样式
.task-list {
  padding: 0 20rpx 20rpx;
}

.list-item-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.card-header {
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  
  .task-name {
    color: #1890ff;
  }
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  
  &.status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.status-progress {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  &.status-completed {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.status-paused {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.card-content-box {
  padding: 20rpx 30rpx 30rpx;
}

.content {
  margin-bottom: 20rpx;
}

.item {
  display: flex;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #666666;
  min-width: 160rpx;
}

.value {
  font-size: 28rpx;
  color: #333333;
  flex: 1;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.progress-bar {
  flex: 1;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
}

.progress-bg {
  flex: 1;
  height: 8rpx;
  background-color: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
  margin-right: 16rpx;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 24rpx;
  color: #666666;
  min-width: 60rpx;
}

.operate {
  display: flex;
  gap: 16rpx;
}

.custom-style {
  height: 60rpx !important;
  font-size: 24rpx !important;
  padding: 0 24rpx !important;
  border-radius: 30rpx !important;
}
</style>